package com.xpgk.xpsoft.user;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.xpgk.common.kit.CacheKitEx;
import com.xpgk.common.kit.ImageKit;
import com.xpgk.common.kit.PathFileKit;
import com.xpgk.common.kit.PubKit;
import com.xpgk.common.tools.ToolCache;
import com.xpgk.model.FrmRight;
import com.xpgk.model.FrmUser;
import com.xpgk.model.User;
import com.xpgk.xpsoft.common.XPSoftService;
import com.xpgk.xpsoft.constants.XPSoftConstant;

public class UserService extends XPSoftService {
	
	public static final UserService me = new UserService();
	
	public User getUserByUserName(String userName){
		String hql = "select *   from User where userName='"+userName+"'";
		return User.dao.findFirst(hql);
	}

	public static String checkUserRecord(FrmUser user) {
		if (user == null)
			return "user is null";
		String value = user.getUSERNAME();
		if (value == null)
			return "userName is null";
		Integer systemID = user.getSYSTEMID();
		if (systemID == null)
			user.setSYSTEMID(XPSoftConstant.systemID);
		value = user.getTYPE();
		if (value == null)
			return "user type is null";
		value = user.getNAME();
		if (value == null)
			return "user name is null";
		value = user.getPHONE();
		if (value == null)
			return "user phone is null";
		value = user.getSTATE();
		if (value == null)
			user.set("state", "0");
		Integer deptID = user.getDEPARTMENTID();
		if (deptID == null)
			return "user departmentID is null";
		return "ok";
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 * @return
	 */
	public static String saveUser(FrmUser user) {
		String ret = checkUserRecord(user);
		if (!ret.equals("ok"))
			return ret;
		user.remove(FrmUser.column_ID);
		if (getUser(user.getUSERNAME()) != null)
			return "userName has exist";
		user.setPASSWORD("null");
		user.save();

		setPassword(user.getUSERNAME(), HashKit.md5("888888"));
		Record userInfo = new Record().set("USERID", user.getID()).set("REGISTTIME", new Date());
		Db.save("FRM_USER_INFO", "USERID", userInfo);
		return "ok";
	}

	/**
	 * 跟新用户角色
	 * 
	 * @param userID
	 * @param role
	 * @return
	 */
	public static String updateUserRole(int userID, Integer[] role) {
		FrmUser user = getUser(userID);
		if (user == null)
			return "not find user";

		Db.update("delete from FRM_USER_ROLE where USERID=?", userID);

		if (role != null && user.getTYPE().equals("2")) {
			List<Record> recordList = new ArrayList<Record>();

			for (int i = 0; i < role.length; i++) {
				Record record = new Record();
				record.set("USERID", userID);
				record.set("ROLEID", role[i]);
				record.set("JYW", HashKit.md5(userID + "userRole" + role[i]));
				recordList.add(record);
			}
			Db.batchSave("FRM_USER_ROLE", recordList, 500);
		}
		CacheKitEx.remove(XPSoftConstant.cacheName, XPSoftConstant.cacheKey_UserRightID(userID));
		return "ok";
	}

	/**
	 * 跟新用户
	 * 
	 * @param user
	 * @return
	 */
	public static String updateUser(FrmUser user) {
		if (user == null || user.getID() == null)
			return "错误用户信息。";
		if (user.update()) {
			FrmUser.cacheAdd(user.getID());
			return "ok";
		}
		return "错误用户信息。";
	}

	/**
	 * 获取指定用户
	 * 
	 * @param userID
	 * @return
	 */
	public static FrmUser getUser(int userID) {
		FrmUser user = FrmUser.cacheGet(userID);
		return user;
	}

	/**
	 * 获取指定用户
	 * 
	 * @param userName
	 * @return
	 */
	public static FrmUser getUser(String userName) {
		FrmUser user = FrmUser.cacheGet(userName);
		return user;
	}

	/**
	 * 返回指定用户的是否有效
	 * 
	 * @param userName
	 * @return
	 */
	public static String getUserState(String userName) {
		FrmUser user = getUser(userName);
		if (user == null)
			return "无效用户。";
		if (!"1".equals(user.getSTATE()))
			return "用户已经被禁用";
		// 所在部门无效
		return "ok";
	}

	/**
	 * 返回指定用户的是否有效IP
	 * 
	 * @param userName
	 * @param clientIP
	 * @return
	 */
	public static String getUserLimitIP(String userName, String clientIP) {
		if (clientIP == null)
			return "ok";
		FrmUser user = getUser(userName);
		if (user == null)
			return "无效用户。";
		if (user.getLIMITIP() == null)
			return "ok";
		// 无效IP
		String ip = user.getLIMITIP();
		if (!PubKit.isBlank(ip)) {
			if (ip.equals(clientIP) || ip.startsWith(clientIP + ",") || ip.endsWith("," + clientIP) || ip.indexOf("," + clientIP + ",") >= 0)
				return "ok";
		}
		return "limit IP";
	}

	/**
	 * 返回指定用户的登录错误次数
	 * 
	 * @param userName
	 * @return
	 */
	public static int getLoginErrNumber(String userName) {
		FrmUser user = getUser(userName);
		if (user == null)
			return 0;
		Integer count = user.getERRORNUMBER();
		if (count == null)
			return 0;
		return count;
	}

	/**
	 * 返回指定用户名和密码是否正确
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	public static boolean validPassword(String userName, String password) {
		FrmUser user = getUser(userName);
		if (user == null)
			return false;
		String t = HashKit.md5(userName + user.getID() + password) + "userpassword";
		// System.out.println(HashKit.md5(t));
		if (HashKit.md5(t).equals(user.getPASSWORD())) {
			return true;
		} else {
			user.setERRORNUMBER(PubKit.ifNull(user.getERRORNUMBER(), 0) + 1);
			if (user.update()) {
				FrmUser.cacheAdd(user.getID());
			}
			return false;
		}
	}

	/**
	 * 设置用户名和密码
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	public static boolean setPassword(String userName, String password) {
		FrmUser user = getUser(userName);
		if (user == null)
			return false;
		String t = HashKit.md5(userName + user.getID() + password) + "userpassword";
		user.set("password", HashKit.md5(t));
		updateUser(user);
		return true;
	}

	/**
	 * 返回指定用户的所有权限
	 * 
	 * @param userID
	 * @return
	 */
	public static List<Record> getUserRights(int userID) {
		return null;
	}

	/**
	 * 判断用户是否拥有权限
	 * 
	 * @param userID
	 * @param rightID
	 * @return
	 */
	public static boolean hasRight(int userID, int rightID) {
		if (userID < 0)
			return false;

		Kv kv = ToolCache.get(XPSoftConstant.cacheKey_UserRightID(userID));
		if (kv == null) {
			List<Record> records = Db.find(Db.getSqlPara("xpSoftUser.findUserRightListByUserID", Kv.by("USERID", userID)));
			if (records == null || records.isEmpty())
				return false;
			kv = Kv.create();
			for (Iterator<Record> iterator = records.iterator(); iterator.hasNext();) {
				Record record = (Record) iterator.next();
				kv.set(PubKit.toInt(record.get("ID")), 0);
			}
			ToolCache.set(XPSoftConstant.cacheKey_UserRightID(userID), kv);
		}
		return kv.containsKey(rightID);
	}

	/**
	 * 判断用户是否拥有权限
	 * 
	 * @param userID
	 * @param uri
	 * @return
	 */
	public static boolean hasRight(int userID, String uri) {
		FrmRight right = FrmRight.cacheGet(uri);
		if (null == right) {
			return false;
		}
		return hasRight(userID, right.getID());
	}

	/**
	 * 刪除用戶所有緩存
	 * 
	 * @param userName
	 * @return
	 */
	public static boolean removeAllCache(String userName) {
		FrmUser user = getUser(userName);
		if (user == null)
			return false;
		int userID = user.getID();

		ToolCache.remove(XPSoftConstant.cacheKey_UserRightID(userID));
		ToolCache.remove(XPSoftConstant.cacheKey_UserMenu(userID));
		FrmUser.cacheRemove(userID);
		return true;
	}

	static public String updateUserDetail(Record userInfo) {
		if (userInfo == null || userInfo.get("USERID") == null)
			return "错误用户信息。";
		if (Db.update("FRM_USER_INFO", "USERID", userInfo)) {
			return "ok";
		}
		return "错误用户信息。";
	}

	// 设置用户头像
	static public Kv setUserPhoto(String userName, UploadFile file) {
		Kv ret = Kv.create();
		String fileName = file.getFileName();
		File uploadFile = file.getFile();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension) || "jpeg".equals(extension) || "bmp".equals(extension)) {
			// 使用缩略图
//			fileName = new ImageKit().thumbnailImage(uploadFile, 150, 150, "thumb_", false);
//			File source = new File(fileName);
			
			String savePath = PathKit.getWebRootPath() + "/upload/images/userPhoto/"+userName;
			String saveFileName = userName + extension;
			try {
				File p = new File(savePath);
				if (!p.exists())
					p.mkdirs();
//				PathFileKit.copyFile(source, new File(savePath + "/" + saveFileName));
				PathFileKit.copyFile(uploadFile, new File(savePath + "/" + saveFileName));
				ret.set("flag", 1);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				ret.set("msg", "文件写入服务器出现错误，请稍后再上传");
				ret.set("flag", 0);
			}
//			source.delete();
			String src = "upload/images/userPhoto/" + userName + "/" + saveFileName;
			ret.set("src", src); // 相对地址，显示图片用
			int userID = UserService.getUser(userName).getInt("id");
			Db.update("update FRM_USER_INFO set PHOTO=? where USERID=?", src, userID);
		} else {
			ret.set("msg", "只允许上传png,jpg,jpeg,gif,bmp类型的图片文件");
			ret.set("flag", 0);
		}
//		uploadFile.deleteOnExit();
		uploadFile.delete();
		return ret;
	}

	// 得到密码等级
	// 1表示单一大写或小写字符 或单一数字或 单一符号 或6位及以下
	// 2表示两者结合,且6位以上
	// 3表示三者或以上结合,且6位以上
	static public int getPasswordLevel(String pwd) {
		return 0;
	}
}
